package com.mucd.chat.service;

import com.mucd.chat.mapper.FriendListMapper;
import com.ruoyi.common.core.domain.FriendList;
import com.ruoyi.common.core.domain.FriendRequest;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author mucd
 * 好友列表service
 */
@Service
@Slf4j
public class FriendListService {

    @Resource
    private FriendListMapper friendListMapper;
    @Resource
    private ISysUserService sysUserService;

    /**
     * 添加好友
     *
     * @param friendRequest 好友请求
     * @return rows
     */
    public int addFriend(FriendRequest friendRequest) {
        //双方都需要成为好友 , 所以需要添加两次

        FriendList friendList = new FriendList();
        friendList.setFriendUserId(friendRequest.getSendUserId());
        friendList.setMyUserId(friendRequest.getReceiveUserId());
        int rowsMy = friendListMapper.addFriend(friendList);

        friendList.setFriendUserId(friendRequest.getReceiveUserId());
        friendList.setMyUserId(friendRequest.getSendUserId());
        int rowsTo = friendListMapper.addFriend(friendList);

        return rowsMy + rowsTo;
    }

    /**
     * 查询好友列表
     *
     * @return 好友列表
     */
    public List<FriendList> selectFriendList() {
        Long userId = SecurityUtils.getUserId();

        List<FriendList> friendList = friendListMapper.selectFriendListByUserId(userId);
        settingUserInfo(friendList);

        return friendList;
    }

    private void settingUserInfo(List<FriendList> friendList) {

        friendList.stream().parallel().forEach(item -> {


            SysUser sysUser = sysUserService.selectUserById(item.getFriendUserId());

            if (sysUser != null) {
                item.setNickName(sysUser.getNickName());
                item.setAvatar(sysUser.getAvatar());
                item.setFriendUserId(sysUser.getUserId());
                item.setPhonenumber(sysUser.getPhonenumber());
            }
        });

    }

}
